// Learn cc.Class:
//  - [Chinese] http://www.cocos.com/docs/creator/scripting/class.html
//  - [English] http://www.cocos2d-x.org/docs/editors_and_tools/creator-chapters/scripting/class/index.html
// Learn Attribute:
//  - [Chinese] http://www.cocos.com/docs/creator/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/editors_and_tools/creator-chapters/scripting/reference/attributes/index.html
// Learn life-cycle callbacks:
//  - [Chinese] http://www.cocos.com/docs/creator/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/editors_and_tools/creator-chapters/scripting/life-cycle-callbacks/index.html
/**
 * 投注面板
 * 11选5任选投注面板
 */
cc.Class({
    extends: cc.Component,

    properties: {
        tgAnySelList:[cc.Toggle], //选择玩法按钮列表
        tgRedBall:cc.Prefab,  //球的预制
        betContent:cc.Node,  //球放置目录
        tgChangeBall: cc.Node, //设胆球
        labTopTitle:cc.Label,  //标头
        labDec: cc.RichText,   //说明
        tgSelect:cc.Toggle,   //机选、清空切换按钮
        edMutipleNum:cc.EditBox,  //投的倍数
        labShowAmount: cc.Label,  //显示共注、倍、元、
        spRedBall:cc.SpriteFrame,  //红球图片
        spYellowBall:cc.SpriteFrame,   //黄球图片
        BASEMONEY:2, //基础投资
        rules:[], //规则
        nums:[],  //数值   
        isMiss:false, //是否开启遗漏
        isNorm:1, //当前模式:0胆拖1标准  
        decContents:[], //说明列表
        names: [],  //标头名字
        betToggleList:[],//球指针列表
        selRedBall:[],//选择球数字列表
        selYellowBall:[],//选择胆球数字列表
        manageCenter: cc.Node,
        curPage:2,   
        curMoney:0,
        curBetNum:0,
        _betManage: null,
    },

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {},

    start () {
        this.initConfig();
        this.initPanel();
    },

    initConfig: function(){
        this.rules = [DEFINE.LOTTERYRULE115.ANYTWO,DEFINE.LOTTERYRULE115.ANYTHREE,DEFINE.LOTTERYRULE115.ANYFOUR,
            DEFINE.LOTTERYRULE115.ANYFIVE,DEFINE.LOTTERYRULE115.ANYSIX,DEFINE.LOTTERYRULE115.ANYSEVEN,
            DEFINE.LOTTERYRULE115.ANYEIGHT];
        this._betManage = this.manageCenter.getComponent("bet_115_pop"); 

        this.nums = ["01","02","03","04","05","06","07","08","09","10","11"]; 
        this.isNorm = 1;
        this.decContents = [
        "<color=#ffffff>至少选2个号码，猜对任意2个开奖号即中</c><color=#f6ca4c>6元宝</color>",
        "<color=#ffffff>至少选3个号码，猜对任意3个开奖号即中</c><color=#f6ca4c>19元宝</color>",
        "<color=#ffffff>至少选4个号码，猜对任意4个开奖号即中</c><color=#f6ca4c>78元宝</color>",
        "<color=#ffffff>至少选5个号码，猜对全部5个开奖号即中</c><color=#f6ca4c>540元宝</color>",
        "<color=#ffffff>至少选6个号码，选号包含5个开奖号即中</c><color=#f6ca4c>90元宝</color>",
        "<color=#ffffff>至少选7个号码，选号包含5个开奖号即中</c><color=#f6ca4c>26元宝</color>",
        "<color=#ffffff>至少选8个号码，选号包含5个开奖号即中</c><color=#f6ca4c>9元宝</color>",
        ];
        //this.names = ["任选二","任选三","任选四","任选五","任选六","任选七","任选八"];

    },

    initPanel:function(){
        for(var j = 0;j<this.nums.length;j++)
        {      
            var ball = cc.instantiate(this.tgRedBall);
            ball.getComponent('bet_sel115_item').init({
                num: this.nums[j],
                miss: ""
            });
            var checkEventHandler = new cc.Component.EventHandler();
            checkEventHandler.target = this.node; 
            checkEventHandler.component = "bet_115_anySelect"
            checkEventHandler.handler = "onClickCallback";
            checkEventHandler.customEventData = j+1;
            ball.getComponent(cc.Toggle).checkEvents.push(checkEventHandler);
            this.betContent.addChild(ball);
            this.betToggleList.push(ball);
        }

        var checkEventHandler = new cc.Component.EventHandler();
        checkEventHandler.target = this.node; 
        checkEventHandler.component = "bet_115_anySelect"
        checkEventHandler.handler = "onChangeBallCallback";
        checkEventHandler.customEventData = "";
        this.tgChangeBall.getComponent(cc.Toggle).checkEvents.push(checkEventHandler);
        this.tgChangeBall.active = false;


        for(var i=0;i<this.tgAnySelList.length;i++)
        {
            var checkEventHandler = new cc.Component.EventHandler();
            checkEventHandler.target = this.node; 
            checkEventHandler.component = "bet_115_anySelect"
            checkEventHandler.handler = "onSelPageCallBack";
            checkEventHandler.customEventData = {
                //name:this.names[i],
                hasNorm:(i==0||i==1||i==this.tgAnySelList.length-1)?1:0,
                pageID:i+2,
                decContent:this.decContents[i]
            };
            this.tgAnySelList[i].getComponent(cc.Toggle).checkEvents.push(checkEventHandler);
        }
        //初始选择第一个小界面
        var temp = this.tgAnySelList[0].getComponent(cc.Toggle).checkEvents[0].customEventData;
        this.onSelPageCallBack(this.tgAnySelList[0],temp);
    },

    onSelPageCallBack:function(toggle, customEventData){
        if(toggle.getComponent(cc.Toggle).isChecked)
        {
            //this.labTopTitle.string = customEventData.name;
            this.labDec.string = customEventData.decContent;
            var hasNorm = customEventData.hasNorm;
            this.curPage = customEventData.pageID;

            if(hasNorm == 0)
            {
                this.tgChangeBall.active = true;
            }
            else
            {
                this.tgChangeBall.active = false;
            }
            this.clearCurSel();
        }
    },

    //清空当前选择
    clearCurSel:function(){
        this.selRedBall.length = 0;
        this.selYellowBall.length = 0;
        for(var i=0;i<this.betToggleList.length;i++)
        {
            this.betToggleList[i].getComponent(cc.Toggle).isChecked = false;
        }
        
        this.isNorm = 1;
        this.tgSelect.getComponent(cc.Toggle).isChecked = false;
        this.tgChangeBall.getComponent(cc.Toggle).isChecked = false;
        this._betManage.setMutipleAmount(1);
        this.checkBet();
    },

    //胆拖
    onChangeBallCallback:function(toggle){
        if(toggle.getComponent(cc.Toggle).isChecked)
        {
             this.isNorm = 0;
             ComponentsUtils.showTips("开始胆拖投注");
        }
        else
        {
             this.isNorm = 1;
        }
        this.updateTgSelect();
    },
    
    updateTgSelect:function(){
        if(this.selRedBall.length>0 || this.selYellowBall.length>0)
        {
            this.tgSelect.getComponent(cc.Toggle).isChecked = true;
            
        }
        else
        {
            if(this.isNorm == 1)
            {
                this.tgSelect.getComponent(cc.Toggle).isChecked = false;
            }
            else
            {
                this.tgSelect.getComponent(cc.Toggle).isChecked = true;
               
            }
        } 
    },

    onClickCallback:function(toggle, customEventData){
        var num = customEventData;
        if(toggle.getComponent(cc.Toggle).isChecked)
        {
            if(this.isNorm == 0)//胆拖
            { 
                var maxNum = this.curPage-1;
                if(this.selYellowBall.length >= maxNum)
                {
                    ComponentsUtils.showTips("胆码最多只能选择"+maxNum.toString()+"个");
                    toggle.getComponent(cc.Toggle).isChecked = false;
                    return;
                }
                this.selYellowBall.push(num);
                toggle.checkMark.spriteFrame = this.spYellowBall;  
                toggle.getComponent("bet_sel115_item").setType(2);
                this.updateTgSelect();
                this.checkBet();
                return;
            }
            else if(this.isNorm == 1)
            {
                this.selRedBall.push(num);
                toggle.checkMark.spriteFrame = this.spRedBall;
                toggle.getComponent("bet_sel115_item").setType(1);
                this.updateTgSelect();
                this.checkBet();
                return;
            }
        }

        var type = toggle.getComponent("bet_sel115_item").getType();
        if(type == 1)
        {
            Utils.removeByValue(this.selRedBall,num);
        }
        else if(type == 2)
        {
            Utils.removeByValue(this.selYellowBall,num);
        }
        toggle.getComponent("bet_sel115_item").setType(0);
        this.updateTgSelect();
        this.checkBet();
    },

    //计算投注规则
    checkBet: function(){
        var bet = 0;
        if(this.selYellowBall.length>0)
        {
            //胆码
            var dan = this.selYellowBall.length;
            //拖码
            var tuo = this.selRedBall.length;
            if(dan <1 || tuo <1)
                bet = 0
            else    
                bet = LotteryUtils.combination(tuo,this.curPage-dan);
           
            if(bet == 1)
            {
                bet = 0;
            }
        }
        else
        {
            bet = LotteryUtils.combination(this.selRedBall.length,this.curPage);
        }

        var muiple = this._betManage.getMutipleAmount();
        this.setShowAmount(muiple,bet);
    },

    //显示投注信息
    setShowAmount:function(mut,bet){
        var issue = 1;//this.getIssueNum();
        var money = mut*bet*this.BASEMONEY*issue;
        this._betManage.setMoney(money);
        this._betManage.setBetNum(bet);
        
        this.labShowAmount.string = "共"+bet+"注"+ mut +"倍"+ issue + "期"+ money+"元宝";
    },

    //选择清空切换
    onSelectCallBack:function(toggle){
        if(this.isNorm == 0)
        {
            toggle.getComponent(cc.Toggle).isChecked = true;
            this.clearCurSel();
        }
        else
        {
            if(toggle.getComponent(cc.Toggle).isChecked)
            {
                this.randomSelectCallBack();
            }
            else
            {
                this.clearCurSel();
            }
        }
    },

    //机选
    randomSelectCallBack:function(){   
        if(this.isNorm == 1)
        {
            this.clearCurSel();
            var randomArray = Utils.getRandomArrayWithArray(this.betToggleList, this.curPage);
            for(var j = 0; j<randomArray.length; j++){
                randomArray[j].getComponent(cc.Toggle).isChecked = true;
                var temp = randomArray[j].getComponent(cc.Toggle).checkEvents[0].customEventData;
                
                this.onClickCallback(randomArray[j].getComponent(cc.Toggle),temp);
            }
            return true;
        }
        return false;
    },

    //投注信息组合
    dataToJson:function(){
        var obj = new Object(); 
        obj.PlayCode = parseInt(this._betManage._lotteryCode + this.rules[this.curPage-2].toString()); 
        var nums = "";
        var num = "";
        if(this.selYellowBall.length>0)
        {
            var ball1 = this.selRedBall;
            var ball2 = this.selYellowBall;
            Utils.sortNum(ball1);
            Utils.sortNum(ball2);
            for(var i = 0;i<ball2.length;i++)
            {
                if(num != "")
                {
                    num+=",";
                }  
                num += ball2[i]>9 ? ball2[i].toString():"0"+ball2[i].toString();
            }
            nums = num;
            num = "";
            for(var i = 0;i<ball1.length;i++)
            {
                if(num != "")
                {
                    num+=",";
                }  
                var oneNum = ball1[i]>9 ? ball1[i].toString():"0"+ball1[i].toString(); 
                num += oneNum;
            }
            nums = nums + "#" + num;   
        }
        else
        {
            var ball = this.selRedBall;
            Utils.sortNum(ball);
            for(var i = 0;i<ball.length;i++)
            {
                if(nums != "")
                {
                    nums+=",";
                }  
                var oneNum = ball[i]>9 ? ball[i].toString():"0"+ball[i].toString(); 
                nums += oneNum;
            }
        }
  
        var arry = [];
        var numArrays = {
                "Multiple":this._betManage.getMutipleAmount(),
                "Bet":this._betManage.getBetNum(),
                "isNorm":this.isNorm,
                "Number":nums//this.isNorm == 0 ? encodeURIComponent(nums):nums
            };
        arry.push(numArrays);
        obj.Data = arry;
        var json = JSON.stringify(obj);
        cc.log("提交订单：" + json);
        return json;
    },

    //是否显示-遗漏数组-显示控件列表-彩种id-规则id
    showMiss:function(toggleList,lotteryid,playCode){
        var recv = function(ret){
            ComponentsUtils.unblock();
            var temparr = [];
            if(ret.Code === 0)
            {
                temparr = ret.Data;
                try {
                    var obj = eval('('+temparr+')');
                    this.setMiss(true,toggleList,obj["o"]);
                } catch (error) {
                
                }  
            }
            else
            {
                ComponentsUtils.showTips(ret.Msg);  
                this.setMiss(true,toggleList,temparr);
            }
        }.bind(this);
        var data = {
            LotteryCode:lotteryid,
            IsuseName:"1",
            PlayCode:playCode,
            TopCount:100
        }
       
        CL.HTTP.sendRequest(DEFINE.HTTP_MESSAGE.GETLOTTERYMISS, data, recv.bind(this),"POST"); 
        ComponentsUtils.block();  
    },

    //是否显示-遗漏数组-显示控件列表
    setMiss:function(isMiss,toggleList,missArry){
        if(isMiss)
        {
            if(missArry.length == toggleList.length)
            {
                if(missArry.length > 0)
                {
                    for(var i=0;i<toggleList.length;i++)
                    {
                        toggleList[i].getComponent('bet_sel115_item').setMissNum(missArry[i]);
                    }
                }
                else
                    toggleList[i].getComponent('bet_sel115_item').setMissNum("--");
            }  
        }
        else
        {
            for(var i=0;i<toggleList.length;i++)
            {
                toggleList[i].getComponent('bet_sel115_item').setMissNum("");
            }
        }   
    },

    // update (dt) {},
});
